package com.driver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.driver.enums.Valid;
import com.driver.mapper.ConfigMapper;
import com.driver.pojo.entity.Config;
import com.driver.service.IConfigService;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 参数配置表 服务实现类
 * </p>
 */
@Service("configService")
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements IConfigService {

    @Override
    public String getValueByNameAndKey(String name, String key) {
        LambdaQueryWrapper<Config> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Config::getName, name)
                .eq(Config::getConfigKey, key)
                .eq(Config::getIsValid, Valid.VALID);
        Config one = super.getOne(wrapper, false);
        if (Objects.isNull(one)) {
            return null;
        } else {
            return one.getConfigValue();
        }
    }

    @Override
    public Double getVoltage() {
        String value = getValueByNameAndKey("set", "voltage");
        try {
            return Double.parseDouble(value);
        } catch (Exception e) {
            return 220d;
        }
    }

    @Override
    public Double getRate() {
        String value = getValueByNameAndKey("set", "rate");
        try {
            return Double.parseDouble(value);
        } catch (Exception e) {
            return 120d;
        }
    }

    @Override
    public void setVoltage(Double voltage) {
        LambdaUpdateWrapper<Config> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Config::getConfigValue, voltage)
                .eq(Config::getName, "set")
                .eq(Config::getConfigKey, "voltage")
                .set(Config::getIsValid, Valid.VALID);
        baseMapper.update(wrapper);
    }

    @Override
    public void setRate(Double rate) {
        LambdaUpdateWrapper<Config> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Config::getConfigValue, rate)
                .eq(Config::getName, "set")
                .eq(Config::getConfigKey, "rate")
                .set(Config::getIsValid, Valid.VALID);
        baseMapper.update(wrapper);
    }

    @Override
    public String getCode() {
        return getValueByNameAndKey("set", "code");
    }

    @Override
    public void setCode(String code) {
        LambdaUpdateWrapper<Config> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Config::getConfigValue, code)
                .eq(Config::getName, "set")
                .eq(Config::getConfigKey, "code")
                .set(Config::getIsValid, Valid.VALID);
        baseMapper.update(wrapper);
    }

}
